#!/usr/bin/env coffee

import {Worker} from 'worker_threads'
import ROOT from '../dir/root'
import {join} from 'path'
import os from 'os'
import {hash} from 'blake3'

CPU = os.cpus().length
if CPU > 2
  CPU = 2

export verify = (难度系数, token, buf)=>
  if hash(
    Buffer.concat [token,buf]
  ).readUIntBE(0,难度系数)
    return false
  return true

THREAD_FILE = join ROOT, "lib/_token.js"

export default (难度系数, buf)=>

  new Promise (resolve)=>
    n = 0
    i = 0
    li = []
    while i < CPU
      worker = new Worker(
        THREAD_FILE
        workerData:[
          难度系数
          buf
          n+i
          CPU
        ]
      )
      worker.once(
        'message'
        (token)=>
          resolve Buffer.from token
          for w from li
            w.terminate()
      )
      li.push worker
      ++i
    return

